import {Component, OnInit, Input, Output, EventEmitter} from '@angular/core';
import {USERAPI} from "../../service/user.api.service";
import {USER} from "../../service/user.service";
import {FormGroup, FormBuilder} from "@angular/forms";
import {SMS} from "../../service/sms.service";
import {WfToast} from "../../utils/toast.utils";
import {mobileValidator, verifyValidator} from "../../utils/validator.utils";

@Component({
  selector: 'app-modify-password-view',
  templateUrl: './modify-password-view.component.html',
  styleUrls: ['./modify-password-view.component.scss']
})
export class ModifyPasswordViewComponent implements OnInit {
  @Input('showModal') public isModalShown:boolean = false;
  @Output('modalClose') public modalClose = new EventEmitter();
  data = {
    username: undefined,
    verifyCode: undefined,
    password: undefined
  }
  password:undefined;
  getVerTitle:string = "获取验证码";
  form:FormGroup;

  timer:any;
  num:number = 60;
  disabled:boolean = false;

  constructor(private USERAPI:USERAPI, private USER:USER, private SMS:SMS, private toast:WfToast, private fb:FormBuilder) {
    this.data.username = this.USER.get().username
    this.form = fb.group({
      username: ['', mobileValidator],
      verifyCode: ['', verifyValidator],
      password: [''],
      password2: [1]
    });
  }

  ngOnInit() {

  }

  doVerify() {
    this.SMS.send(this.data.username, (data:any) => console.log("sms", data));
    this.disabled = true;
    this.timer = setInterval(() => {
      this.num--;
      this.getVerTitle = this.num + '秒';
      if (this.num === 0) {
        clearInterval(this.timer);
        this.disabled = false;
        this.num = 60;
        this.getVerTitle = '获取验证码';
      }
    }, 1000);
  }

  commit() {
    if (this.password == this.data.password) {
      let close = this.modalClose;
      this.USERAPI.modPwd(this.data, (resp:any) => {
        close.emit(false);
        this.toast.msg('密码修改成功');
      });
    } else {
      this.toast.msg('两次密码不一致,请重新输入');
      this.password = undefined;
      this.data.password = undefined;
    }

  }

  public showModal():void {
    this.isModalShown = true;
  }

  public onHidden():void {
    this.isModalShown = false;
  }

}
